<?php
/**
 * ==============================================
 * Copy right 2015-2016 http://wei.meididi88.com
 * ----------------------------------------------
 * This is not a free software, without any authorization is not allowed to use and spread.
 * ==============================================
 * @author: hy
 * @date: 2015-9-10
 * @version: v1.0.0
 */
namespace Common\Model;

use Think\Model;

/**
 * 用户优惠券Model模型类
 */
class UserCouponModel extends Model{
	
	/**
	 * 获取用户的优惠券列表
	 * 
	 * @param number $userId		用户编号
	 * @param number $expiresTime	过期时间
	 * 
	 * @return array|boolean
	 */
	public function getUserCouponList($userId, $expiresTime = 0) {
		$where = array('user_id' => $userId);
		
		$where ['status'] = 1;
		$where [] = "((expires_time>$expiresTime and expiry_type!=1) OR expiry_type=1)";
		
		return $this->where($where)->select();
	}
	
	/**
	 * @param number $userId
	 * @param number $expiresTime
	 * @return Ambigous <\Think\mixed, string, boolean, NULL, mixed, unknown, object>
	 */
	public function getUserLostCouponList($userId, $expiresTime = 0) {
		$where = array('user_id' => $userId);
		$where [] = "((expires_time<$expiresTime and status=1 AND expiry_type!=1) OR status=0)";
		
		return $this->where($where)->select();
	}
	
	/**
	 * 获取用户可用优惠券
	 * 
	 * @param number $userId	用户编号
	 * @param number $pay		订单支付金额
	 * 
	 * @return array|boolean
	 */
	public function getCanUseCouponByPay($userId, $pay) {
		$where = array(
			'user_id' => $userId, 
			'status' => 1,
			'expiry_type=1 or (expiry_type!=1 and expires_time>'.time().')'
		);
		
		$unlimitedwhere ['c_type'] = 2;
		$unlimitedwhere ['money_amount'] = array('elt', $pay);
		
		$canUseSql = $this->where(array_merge($where, array('c_type' => array('neq', 2), 'money_max' => array('elt', $pay))))->buildSql();
		return $this->where(array_merge($where, $unlimitedwhere))
			->union($canUseSql)
		->select();
	}
}

?>